package com.sk.weichat.ui.message.multi;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.GroupMembersHeadAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseComparator;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.groupchat.GroupMembersListActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.SearchUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewHolder;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * 转让群组
 */
public class GroupTransferActivity extends BaseActivity {
    private LinearLayout ll_main;
    private RelativeLayout rt_title;
    private RelativeLayout layout_search;
    private View headView;
    private ListView mListView;
    private GroupTransferAdapter mAdapter;
    private List<BaseSortModel<RoomMember>> mSortRoomMember;
    private SideBar mSideBar;
    private TextView mTextDialog;
    private String mRoomId;
    private String mRoomJid;
    private String mSelectedUserId;
    private String mSelectedUserName;
    private RecyclerView recy_head;
    private GroupMembersHeadAdapter membersHeadAdapter;
    private List<BaseSortModel<RoomMember>> mSortHeadRoomMember = new ArrayList<>();

    private List<BaseSortModel<RoomMember>> sortedList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        mRoomId = getIntent().getStringExtra("roomId");
        mRoomJid = getIntent().getStringExtra("roomJid");

        initActionBar();
        initData();
        initView();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText("群主管理权转让");
        mSideBar = (SideBar) findViewById(R.id.sidebar);
    }

    private void initData() {
        mSortRoomMember = new ArrayList<>();

        DialogHelper.showDefaulteMessageProgressDialog(this);
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(this, ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            // TODO: sql层直接过滤掉群主本人，
            List<RoomMember> data = RoomMemberDao.getInstance().getRoomMemberForTransfer(mRoomId, coreManager.getSelf().getUserId());
            Map<String, Integer> existMap = new HashMap<>();
             sortedList = SortHelper.toSortedModelList(data, existMap, member -> {
                String name = member.getCardName();
                return name;
            });
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                mSideBar.setExistMap(existMap);

                for (int i = 0; i < sortedList.size(); i++) {
                    if (sortedList.get(i).getBean().getRole()==2){
                        mSortHeadRoomMember.add(sortedList.get(i));
                    }else {
                        mSortRoomMember.add(sortedList.get(i));
                    }
                }
                if (mSortHeadRoomMember.size()>0){
                    membersHeadAdapter.notifyDataSetChanged();
                    mListView.addHeaderView(headView);
                }
                mAdapter.setData(mSortRoomMember);
            });
        });

    }

    private void initView() {
        mListView =  findViewById(R.id.list_view);
        headView = LayoutInflater.from(this).inflate(R.layout.layout_recy, mListView, false);
        TextView tv_title = headView.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("管理员");
        recy_head = headView.findViewById(R.id.recy_had_add);
        membersHeadAdapter = new GroupMembersHeadAdapter(mSortHeadRoomMember);
        recy_head.setLayoutManager(new LinearLayoutManager(this));
        recy_head.setNestedScrollingEnabled(true);
        membersHeadAdapter.setHasStableIds(true);
        recy_head.setAdapter(membersHeadAdapter);
        mAdapter = new GroupTransferAdapter(mSortRoomMember);
        mListView.setAdapter(mAdapter);


        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                    showTextDialog(s);

                }
            }
        });
        ll_main = findViewById(R.id.ll_main);
        rt_title = findViewById(R.id.rt_title);
        layout_search = findViewById(R.id.layout_search);
        layout_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SearchUtils(GroupTransferActivity.this, rt_title,
                        ll_main, "请输入昵称或备注名", sortedList, new SearchUtils.onItemClickOListener() {
                    @Override
                    public void onSearchItemClick(RoomMember roomMember) {

                        mSelectedUserId = roomMember.getUserId();
                        mSelectedUserName = roomMember.getCardName();
                        SelectionFrame selectionFrame = new SelectionFrame(mContext);

                        selectionFrame.setSomething(null, getString(R.string.tip_set_group_owner_place_holder, mSelectedUserName), new SelectionFrame.OnSelectionFrameClickListener() {
                            @Override
                            public void cancelClick() {

                            }

                            @Override
                            public void confirmClick() {
                                transferGroup();
                            }
                        });
                        selectionFrame.show();
                    }
                }).showSearchBar();
            }
        });
        membersHeadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                RoomMember roomMember =mSortHeadRoomMember.get(position).bean;
                mSelectedUserId = roomMember.getUserId();
                mSelectedUserName = roomMember.getShowName();

                SelectionFrame selectionFrame = new SelectionFrame(mContext);

                selectionFrame.setSomething(null, getString(R.string.tip_set_group_owner_place_holder, mSelectedUserName), new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {

                    }

                    @Override
                    public void confirmClick() {
                        transferGroup();
                    }
                });
                selectionFrame.show();
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                BaseSortModel<RoomMember> baseSortModel;

                if (mSortHeadRoomMember.size()>0){
                    baseSortModel = mSortRoomMember.get(position-1);
                }else {
                    baseSortModel = mSortRoomMember.get(position);
                }
                RoomMember roomMember = baseSortModel.bean;
                mSelectedUserId = roomMember.getUserId();
                Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(),roomMember.getUserId());
                if (friend!=null){
                    mSelectedUserName = TextUtils.isEmpty(friend.getRemarkName())?friend.getNickName():friend.getRemarkName();
                }else {
                    mSelectedUserName = roomMember.getCardName();
                }
                SelectionFrame selectionFrame = new SelectionFrame(mContext);

                selectionFrame.setSomething(null, getString(R.string.tip_set_group_owner_place_holder, mSelectedUserName), new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {

                    }

                    @Override
                    public void confirmClick() {
                        transferGroup();
                    }
                });
                selectionFrame.show();
            }
        });
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 转让群主
     */
    private void transferGroup() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("toUserId", mSelectedUserId);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_TRANSFER)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            FriendDao.getInstance().updateRoomCreateUserId(coreManager.getSelf().getUserId(),
                                    mRoomJid, mSelectedUserId);
                            EventBus.getDefault().post(new EventGroupStatus(10002, 0));
                            ToastUtil.showToast(mContext,"转让成功");
                            finish();
                        } else {
                            ToastUtil.showToast(mContext,result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    class GroupTransferAdapter extends BaseAdapter implements SectionIndexer {
        List<BaseSortModel<RoomMember>> mSortRoomMember;

        GroupTransferAdapter(List<BaseSortModel<RoomMember>> sortRoomMember) {
            this.mSortRoomMember = new ArrayList<>();
            this.mSortRoomMember = sortRoomMember;
        }

        public void setData(List<BaseSortModel<RoomMember>> sortRoomMember) {
            this.mSortRoomMember = sortRoomMember;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mSortRoomMember.size();
        }

        @Override
        public Object getItem(int position) {
            return mSortRoomMember.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.row_transfer, parent, false);
            }
            TextView catagoryTitleTv = ViewHolder.get(convertView, R.id.catagory_title);
            ImageView avatarImg = ViewHolder.get(convertView, R.id.avatar_img);
//            TextView roleS = ViewHolder.get(convertView, R.id.roles);
            TextView userNameTv = ViewHolder.get(convertView, R.id.user_name_tv);

            // 根据position获取分类的首字母的Char ascii值
            int section = getSectionForPosition(position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == getPositionForSection(section)) {
                catagoryTitleTv.setVisibility(View.VISIBLE);
                catagoryTitleTv.setText(mSortRoomMember.get(position).getFirstLetter());
            } else {
                catagoryTitleTv.setVisibility(View.GONE);
            }
            RoomMember member = mSortRoomMember.get(position).getBean();
            if (member != null) {
                AvatarHelper.getInstance().displayAvatar(member.getUserId(), avatarImg, true);
                Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(),member.getUserId());
                if (friend!=null){
                    userNameTv.setText(TextUtils.isEmpty(friend.getRemarkName())?friend.getNickName():friend.getRemarkName());
                }else {
                    userNameTv.setText(member.getShowName());
                }
//                userNameTv.setText(member.getShowName());
            }
            return convertView;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        @Override
        public int getPositionForSection(int section) {
            for (int i = 0; i < getCount(); i++) {
                String sortStr = mSortRoomMember.get(i).getFirstLetter();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public int getSectionForPosition(int position) {
            return mSortRoomMember.get(position).getFirstLetter().charAt(0);
        }
    }
}
